<template>
  <div class="my-certificates-container">
    <el-card class="page-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="header-title">我的荣誉证书</span>
        </div>
      </template>

      <el-empty v-if="loading" description="加载中..."></el-empty>
      <el-empty v-else-if="certificates.length === 0" description="暂无证书，快去参加竞赛赢取吧！">
        <el-button type="primary" @click="goToContests">浏览竞赛</el-button>
      </el-empty>

      <el-row :gutter="20" v-else>
        <el-col v-for="cert in certificates" :key="cert.id" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="certificate-card" shadow="hover">
            <div class="cert-image-placeholder">
              <el-icon><Medal /></el-icon>
              <span>{{ cert.contestName }}</span>
            </div>
            <div class="cert-info">
              <p class="cert-title"><strong>{{ cert.contestName }}</strong></p>
              <p class="cert-rank">荣获：{{ cert.rankString || '参与奖' }}</p>
              <p class="cert-date">颁发日期：{{ formatDate(cert.issueDate) }}</p>
              <p class="cert-number">证书编号：{{ cert.certificateNumber }}</p>
            </div>
            <template #footer>
              <div class="cert-footer">
                 <el-button 
                    type="primary" 
                    :icon="Download" 
                    @click="downloadCertificate(cert.id, cert.certificateNumber)"
                    plain
                  >
                    下载证书
                  </el-button>
              </div>
            </template>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElCard, ElRow, ElCol, ElButton, ElIcon, ElEmpty } from 'element-plus';
import { Medal, Download } from '@element-plus/icons-vue';
import { getMyCertificatesList } from '@/api/certificate';
import { formatDate } from '@/utils/format'; // Assuming you have a date formatting utility
import { API_BASE_URL } from '@/config'; // 导入API基础URL
import axios from 'axios';

const router = useRouter();
const certificates = ref([]);
const loading = ref(true);

const fetchCertificates = async () => {
  loading.value = true;
  try {
    const res = await getMyCertificatesList();
    if (res.code === 200 && res.data) {
      certificates.value = res.data;
    } else {
      ElMessage.error(res.message || '获取证书列表失败');
      certificates.value = []; // Clear on error
    }
  } catch (error) {
    console.error("Error fetching certificates:", error);
    ElMessage.error('获取证书列表失败，请检查网络或稍后再试');
    certificates.value = []; // Clear on error
  }
  loading.value = false;
};

const downloadCertificate = async (certificateId, certificateNumber) => {
  if (!certificateId) {
    ElMessage.error('无效的证书ID');
    return;
  }

  try {
    // 获取token
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('未登录或登录已过期');
      return;
    }

    // 使用axios进行下载，携带token
    const response = await axios({
      url: `${API_BASE_URL}/certificates/download/${certificateId}`,
      method: 'GET',
      responseType: 'blob', // 指定响应类型为blob
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    // 创建下载链接
    const blob = new Blob([response.data], { type: response.headers['content-type'] });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 从Content-Disposition头中提取文件名，如果没有则使用默认值
    let filename = `${certificateNumber || 'certificate'}.png`;
    const contentDisposition = response.headers['content-disposition'];
    if (contentDisposition) {
      const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
      const matches = filenameRegex.exec(contentDisposition);
      if (matches != null && matches[1]) {
        filename = matches[1].replace(/['"]/g, '');
      }
    }
    
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('证书开始下载...');
  } catch (error) {
    console.error('下载证书失败:', error);
    ElMessage.error('下载证书失败，请稍后再试');
  }
};

const goToContests = () => {
  router.push('/contest/list'); // Adjust if your contest list route is different
};

onMounted(() => {
  fetchCertificates();
});

</script>

<style lang="scss" scoped>
.my-certificates-container {
  padding: 20px;
  background-color: #f4f6f8; // Light background for the page
  min-height: calc(100vh - 50px); // Adjust based on your header/navbar height
}

.page-card {
  border-radius: 12px;
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .header-title {
      font-size: 22px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.certificate-card {
  margin-bottom: 20px;
  border-radius: 10px; // Softer corners
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
  }

  .cert-image-placeholder {
    height: 160px;
    background-color: #eef2f5; // Cute, soft placeholder color
    border-radius: 8px 8px 0 0; // Rounded top corners
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #777;
    text-align: center;
    padding: 10px;

    .el-icon {
      font-size: 50px;
      margin-bottom: 10px;
      color: #a0cfff; // A soft blue
    }
    span {
      font-size: 14px;
      font-weight: 500;
    }
  }

  .cert-info {
    padding: 18px;
    p {
      margin: 0 0 10px 0;
      font-size: 14px;
      color: #555;
      line-height: 1.6;
    }
    .cert-title strong {
      font-size: 16px;
      color: #333;
      font-weight: 600;
    }
    .cert-rank {
      color: #E6A23C; // Gold-ish color for rank
      font-weight: 500;
    }
    .cert-date,
    .cert-number {
      font-size: 12px;
      color: #888;
    }
  }

  .cert-footer {
    display: flex;
    justify-content: flex-end; // Button to the right
    padding: 10px 18px; // Add some padding
    border-top: 1px solid #f0f0f0;
  }
}

.el-empty {
  padding: 40px 0;
  .el-button {
    margin-top: 20px;
  }
}

</style> 